package com.tanhua.dubbo.api;

import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLineService;
import com.tanhua.model.dimain.Question;
import com.tanhua.model.mongo.Friend;
import com.tanhua.model.mongo.Movement;
import com.tanhua.model.mongo.MovementTimeLine;
import com.tanhua.model.vo.PageResult;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author 杰哥不要啦~
 * @date 2021/11/1
 */
@DubboService
public class MovementApiImpl implements MovementApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private TimeLineService timeLineService;


    //发布动态
    @Override
    public void pubish(Movement movement) {
        //1、保存动态详情
        //设置PID
        try {
            movement.setPid(idWorker.getNextId("movement"));
            //设置时间
            movement.setCreated(System.currentTimeMillis());
            mongoTemplate.save(movement);

            /**
             * 这段代码抽取到mongo-uttils里了开启异步多线程缓解好友多的压里
             */
            //     //2、查询当前用户的好友数据
       //     Criteria criteria = Criteria.where("UserId").is(movement.getUserId());
       //     Query query = Query.query(criteria);
       //     List<Friend> friends = mongoTemplate.find(query, Friend.class);
       //     //3、循环好友数据，构建时间线数据存入数据库
       //     for (Friend friend : friends) {
       //        MovementTimeLine timeLine = new MovementTimeLine();
       //         timeLine.setMovementId(movement.getId());
       //         timeLine.setUserId(friend.getUserId());
       //         timeLine.setFriendId(friend.getFriendId());
       //         timeLine.setCreated(System.currentTimeMillis());
       //         mongoTemplate.save(timeLine);
       //     }
            timeLineService.saveTimeLine(movement.getUserId(),movement.getId());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public PageResult findByUserId(Long userId, Integer page, Integer pagesize) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria).skip((page -1 ) * pagesize).limit(pagesize)
                .with(Sort.by(Sort.Order.desc("created")));
        List<Movement> movements = mongoTemplate.find(query, Movement.class);
        return new PageResult(page,pagesize,0l,movements);
    }
}
